import { drizzle } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import dotenv from 'dotenv'
import { recordsTable } from './schema';
import { and, eq } from 'drizzle-orm';

dotenv.config();

// 检查 DATABASE_URL 是否有效
const databaseUrl = process.env.DATABASE_URL;
if (!databaseUrl || databaseUrl === 'your_database_url_here') {
    console.error('❌ 数据库连接 URL 未配置！');
    console.error('请在 .env 文件中设置有效的 DATABASE_URL');
    console.error('例如: DATABASE_URL=postgresql://username:password@localhost:5432/database_name');
    process.exit(1);
}

const client = postgres(databaseUrl);
const db = drizzle({ client });

export default db;

export const createRecord = async (userId: string, amount: number, title: string, date: Date) => {
    // YYYY-MM-DD
    const dateObj = new Date(date)
    const amountInCents = amount * 100
    try {
        const record = await db.insert(recordsTable).values({
            userId,
            amount: amountInCents,
            title,
            date: dateObj,
        })
        return record
    } catch (error) {
        console.log(error)
        return null
    }
}

export const getRecords = async (userId: string, date: string) => {
    // YYYY-MM-DD
    const dateObj = new Date(date)
    try {
        let records = await db.select().from(recordsTable).where(
            and(
                eq(recordsTable.userId, userId),
                eq(recordsTable.date, dateObj)
            )
        )
        // records 金额 * 100
        records.forEach(record => {
            record.amount = record.amount / 100
        })
        return records
    } catch (error) {
        console.log(error)
        return null
    }
}